package com.sgcc.nfc.lock.presentation.main

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.sgcc.nfc.lock.R
import com.sgcc.nfc.lock.core.storage.TokenManager
import com.sgcc.nfc.lock.databinding.ActivityMainBinding
import com.sgcc.nfc.lock.presentation.auth.LoginActivity
import com.sgcc.nfc.lock.presentation.main.viewmodel.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private val viewModel: MainViewModel by viewModels()
    private lateinit var navController: NavController

    @Inject
    lateinit var tokenManager: TokenManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!ensureAuthenticatedOnLaunch()) {
            return
        }
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        setupNavigation()
        observeViewModel()
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            if (!hasValidSession()) {
                navigateToLogin()
            }
        }
    }

    private fun setupNavigation() {
        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController
        binding.bottomNavigation.setupWithNavController(navController)
        navController.addOnDestinationChangedListener { _, destination, _ ->
            viewModel.setToolbarTitle(destination.label?.toString() ?: getString(R.string.app_name))
            viewModel.setBottomBarVisible(
                destination.id in setOf(
                    R.id.homeFragment,
                    R.id.roomsFragment,
                    R.id.locksFragment,
                    R.id.mapFragment,
                    R.id.profileFragment
                )
            )
        }
    }

    private fun observeViewModel() {
        viewModel.toolbarTitle.observe(this) { title ->
            supportActionBar?.title = title
        }
        viewModel.isBottomBarVisible.observe(this) { isVisible ->
            binding.bottomNavigation.isVisible = isVisible
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_toolbar_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_map -> {
                if (navController.currentDestination?.id != R.id.mapFragment) {
                    navController.navigate(R.id.mapFragment)
                }
                true
            }
            android.R.id.home -> navController.navigateUp() || super.onOptionsItemSelected(item)
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun ensureAuthenticatedOnLaunch(): Boolean {
        val valid = runBlocking { hasValidSession() }
        if (!valid) {
            navigateToLogin()
        }
        return valid
    }

    private suspend fun hasValidSession(): Boolean {
        val token = tokenManager.accessToken.first()
        val expiresAt = tokenManager.expiresAt.first() ?: 0L
        val isExpired = expiresAt > 0 && System.currentTimeMillis() > expiresAt
        if (token.isNullOrBlank() || isExpired) {
            tokenManager.clear()
            return false
        }
        return true
    }

    private fun navigateToLogin() {
        if (isFinishing || isDestroyed) return
        startActivity(Intent(this, LoginActivity::class.java))
        finish()
    }
}

